package cn.conac.rc.auth.service;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import cn.conac.rc.auth.entity.PermissionEntity;
import cn.conac.rc.auth.repository.PermissionRepository;
import cn.conac.rc.auth.vo.PermissionVo;
import cn.conac.rc.framework.jpa.Criteria;
import cn.conac.rc.framework.jpa.Restrictions;
import cn.conac.rc.framework.service.GenericService;

@Service
public class PermissionService extends GenericService<PermissionEntity, String> {
	@Autowired
	private PermissionRepository permissionRepository;

	/**
	 * 获取权限
	 * @param id
	 * @return
	 */
	public PermissionEntity findById(String id){
		return permissionRepository.findById(id);
	}

	/**
	 * 获取权限
	 * @param permissionName
	 * @return
	 */
	public PermissionEntity findByPermissionName(String permissionName){
		return permissionRepository.findByPermissionName(permissionName);
	}
	
	/**
	 * 查询权限列表
	 * @param permission
	 * @return
	 * @throws Exception
	 */
	public Page<PermissionEntity> list(PermissionVo permission) throws Exception {
        try {
            Pageable pageable = new PageRequest(permission.getPage(), permission.getSize());
            Criteria<PermissionEntity> dc = this.createCriteria(permission);
            return permissionRepository.findAll(dc, pageable);
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }
	
	/**
	 * 查询权限列表条件拼接
	 * @param permission
	 * @return
	 */
	private Criteria<PermissionEntity> createCriteria(PermissionEntity permission) {
		Criteria<PermissionEntity> dc = new Criteria<PermissionEntity>();
		if (StringUtils.isNotBlank(permission.getPermissionName())) {
			dc.add(Restrictions.like("permission", permission.getPermissionName(), true));
		}
		return dc;
	}
	
	/**
	 * 保存权限
	 * @param permission
	 */
	public void addPermission(PermissionEntity permission){
		this.save(permission);	
	}
	
	/**
	 * 通过角色id查询权限
	 * @param id
	 */
	public List<PermissionEntity> findPermissionsByRoleId(String id){
		return permissionRepository.findPermissionsByRoleId(id);
	}
}

